package resource

import (
    "encoding/json"
    "fcs-api/src/app/model"
    "fcs-api/src/app/utils"
    "fmt"
    "time"

    "git.inspur.com/x/common/loggerfactory"
    "k8s.io/apimachinery/pkg/util/wait"
)

var logger = loggerfactory.GetLogger()

var NeedMonitoring = true
var clusterSchedulePeriod = time.Minute
var clusterStopCh chan struct{}

type ClusterList struct {
    TotalCount      int64 `json:"totalCount"`
    RecordsFiltered int64 `json:"recordsFiltered"`
    Result          []*ClusterInfo
}

type ClusterInfo struct {
    Uuid        string `json:"uuid"`
    DisplayName string `json:"displayName"`
    Vip         string `json:"vip"`
    Eip         string `json:"eip"`
    FloatingIps string `json:"FloatingIps"`
}

func MonitoringCluster() {
    clusterStopCh = make(chan struct{})
    go wait.Until(getFcsCluster, clusterSchedulePeriod, clusterStopCh)
}

func getFcsCluster() {
    if !NeedMonitoring {
        close(clusterStopCh)
        return
    }
    token := utils.GetAdminToken()
    if token != "" {
        token = "bearer " + token
        clusterListUrl := "cks/cluster/v1/clusters/overview?size=6&index=1&name=fcs-cluster&status=running"
        clusterInfoUrl := "cks/cluster/v1/clusters/%s"
        url := model.Base.IceHost + clusterListUrl
        // 获取集群列表中名为fcs-cluster的集群
        body, err := utils.HttpReq(url, token, "GET", nil, nil)
        if err != nil {
            logger.Error("getFcsCluster: Query ice cluster list error %s", err.Error())
            return
        }
        clusterList := new(ClusterList)
        err = json.Unmarshal(body, clusterList)
        if err != nil {
            logger.Error("getFcsCluster: Unmarshal ice cluster list response body error %s, body is %s",
                err.Error(), string(body))
            return
        }
        if clusterList.TotalCount == 0 || len(clusterList.Result) == 0 {
            _ = logger.Warn("getFcsCluster: no fcs cluster detect")
            return
        }
        clusterId := clusterList.Result[0].Uuid
        url = model.Base.IceHost + fmt.Sprintf(clusterInfoUrl, clusterId)
        // 获取fcs-cluster集群详情
        body, err = utils.HttpReq(url, token, "GET", nil, nil)
        if err != nil {
            logger.Error("getFcsCluster: Query ice cluster info error %s body is %s",
                err.Error(), string(body))
            return
        }
        clusterInfo := new(ClusterInfo)
        err = json.Unmarshal(body, clusterInfo)
        if err != nil {
            logger.Error("getFcsCluster: Unmarshal ice cluster info response body error %s", err.Error())
            return
        }
        cluster := &model.Cluster{
            Id:                  clusterInfo.Uuid,
            ClusterName:         clusterInfo.DisplayName,
            ApiserverIps:        clusterInfo.FloatingIps,
            ClusterMasterPasswd: "",
            Vip:                 clusterInfo.Vip,
        }
        // 将集群信息插入数据库
        _, err = model.CreateCluster(cluster)
        if err != nil {
            logger.Error("getFcsCluster: insert info db %s", err.Error())
            return
        }
        close(clusterStopCh)
    }
}
